package api

import (
	"fmt"
	"net/http"
	"os"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-basic/uuid"
)

func UploadImage(c *gin.Context) {
	file, err := c.FormFile("image")
	if err != nil {
		c.JSON(200, gin.H{"message": err.Error()})
		return
	}

	storage_path := fmt.Sprintf("upload/%s/", time.Now().Format("20060601"))
	if _, err := os.Stat(storage_path); err != nil {
		if err := os.Mkdir(storage_path, 0777); err != nil {
			c.JSON(200, gin.H{"message": err.Error()})
			return
		}
	}

	ext := path.Ext(file.Filename)
	uuid := uuid.New()
	filename := fmt.Sprintf("%s%s%s", storage_path, uuid, ext)

	if err := c.SaveUploadedFile(file, filename); err == nil {
		image_uri := "/" + filename
		c.JSON(http.StatusOK, gin.H{"status": "success", "data": image_uri})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}

}
